<template>
  <el-card>
    <!-- 单据编号放在右上角 -->
    <template #header>
      <div class="card-header">
        <h1 class="title-center">采购单</h1>
        <span class="document-number">单据编号：<u>{{ form.yclcg_code }}</u></span>
      </div>
    </template>

    <el-form :model="form" label-width="120px">
      <!-- 入库仓库、供应商、经手人、业务日期放在一行 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="入库仓库*">

            <el-select v-model="form.yclcg_ruck" placeholder="请选择所属仓库">
              <el-option v-for="option in warehouseOptions" :key="option.value" :label="option.label"
                :value="option.value"></el-option>
            </el-select>
          </el-form-item>

        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商">
            <el-select v-model="form.yclcg_gys" placeholder="请选择供应商名称/编码">
              <el-option v-for="option in gysOptions" :key="option.value" :label="option.label"
                :value="option.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="经手人">
            <el-select v-model="form.yclcg_ry" placeholder="请选择">
              <el-option v-for="option in jsrOptions" :key="option.value" :label="option.label"
                :value="option.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务日期">
            <el-date-picker v-model="form.yclcg_time" type="date" placeholder="请选择日期" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 表格部分 -->
      <el-table :data="form1" style="width: 100%; margin-bottom: 20px;" border
        :cell-style="{ padding: '8px', textAlign: 'center' }"
        :header-cell-style="{ background: '#f5f7fa', textAlign: 'center' }">
        <!-- 表格列定义 -->
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="物料编码" align="center">
          <template #default="scope">
            <span @click="openMaterialDialog(scope.row)" style="cursor: pointer;">
              {{ scope.row.wl_code || '点击选择物料' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="物料名称" align="center">
          <template #default="scope">
            <span>{{ scope.row.wl_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.yclcg_sl" type="number" @blur="calculateSubtotal(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.wl_dw_name" />
          </template>
        </el-table-column>
        <el-table-column label="单价（元）" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.wl_dj" type="number" />
          </template>
        </el-table-column>
        <el-table-column label="小计（元）" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.yclcg_xj" disabled />
          </template>
        </el-table-column>
        <el-table-column label="备注" width="200" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.bz" />
          </template>
        </el-table-column>
        <!-- 删除图标列 -->
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-icon class="delete-icon" @click="deleteRow(scope.$index)">
                <Delete />
              </el-icon>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 合计行 -->
        <template #append>
          <div style="display: flex; justify-content: flex-end; padding: 8px; background: #f5f7fa;">
            <span style="font-weight: bold; margin-right: 20px;">合计：</span>
            <span style="font-weight: bold;">{{ calculateTotal() }} 元</span>
          </div>
        </template>
      </el-table>

      <!-- 折扣率、折扣金额、附加金额、结算方式 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="折扣率%">
            <el-input v-model="form.yclcg_zkl" type="number" @blur="calculateDiscountratel(form)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="折扣金额（元）">
            <el-input v-model="form.yclcg_zkje" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="附加金额（元）">
            <el-input v-model="form.yclcg_fjje" type="number" @blur="calculateReceivedAmount(form)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结算方式">
            <el-select v-model="form.yclcg_jsfs" placeholder="请选择">
              <el-option label="现金" value="cash" />
              <el-option label="信用卡" value="creditCard" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 单据备注 -->
      <el-form-item label="单据备注">
        <el-input v-model="form.djbz" type="textarea" />
      </el-form-item>

     
      <!-- 总计金额和实收金额 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="总计金额">
            <el-input v-model="form.yclcg_zje" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实收金额">
            <el-input v-model="form.yclcg_ssje" type="number" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="danger" @click="onCancel">取消</el-button>
        <!-- <el-button type="primary" @click="onSubmit">提交审核</el-button> -->
        <el-button @click="onSave">保存</el-button>
      </el-form-item>

      <!-- 选择物料的模态框 -->
      <el-dialog v-model="materialDialogVisible" title="选择物料" width="80%">
        <el-table ref="materialTable" :data="materialList" @selection-change="handleMaterialSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="物料编码" prop="wl_code" />
          <el-table-column label="物料名称" prop="wl_name" />
          <el-table-column label="物料分类" prop="wl_fl_name" />
          <el-table-column label="制造类型" prop="wl_type_name" />
          <el-table-column label="制造方式" prop="wl_ly" />
          <el-table-column prop="wl_state" label="状态" width="100">
            <template #default="{ row }">
              <span v-if="row.wl_state === 1">启用</span>
              <span v-else-if="row.wl_state === 2">禁用</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 模态框底部按钮 -->
        <template #footer>
          <el-button @click="materialDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMaterialSelection">确定</el-button>
        </template>
      </el-dialog>
    </el-form>
  </el-card>
</template>

<script>
import { ref, reactive, onMounted,computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';
import router from '@/router';

export default {
  name: 'PurchaseOrder',
  setup() {
    // const userId = localStorage.getItem('userId');
    //获取登录角色数据
    const uid=computed(()=>{
             return sessionStorage.getItem('u');
      })
      let userId=reactive({
              id:uid
      })
    const materialTable = ref(null);
    const warehouseOptions = ref([]);
    const gysOptions = ref([]);
    const jsrOptions = ref([]);
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
    const day = String(now.getDate()).padStart(2, '0'); // 补零

    // 生成四位随机数
    const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

    // 拼接时间字符串和随机数
    const formattedTime = `${year}${month}${day}`;
    let id = `cg${formattedTime}${randomNumber}`

    const form = ref({
      yclcg_id: '',
      yclcg_code: id,
      yclcg_ruck: '',
      yclcg_gys: '',
      yclcg_ry: '',
      yclcg_time: '',

      yclcg_zkl: '',
      yclcg_zkje: '',
      yclcg_fjje: '',
      yclcg_jsfs: '',
      djbz: '',
      yclcg_zje: '',
      yclcg_ssje: '',
      yclcg_djzt: '',
    });
    const form1 = ref([
      {
        yclcgxq_code: '',
        wl_code: '', // 物料编码
        wl_name: '', // 物料名称
        yclcg_sl: '',
        wl_dw_name: '',
        wl_dj: '',
        yclcg_xj: '',
        bz: '',
        yclcgxq_ydhsl: '',
      }
    ]);
    const uploadRef = ref(null)
    const fileList = ref([])
    const saving = ref(false)
    const uploadData = ref({
      yclcg_code: id, // 示例参数
      attachments_lx: 1, // 示例参数
      create_by: '' // 示例参数
    })

    // 物料选择相关状态
    const materialDialogVisible = ref(false); // 控制模态框显示
    const materialFilter = reactive({
      type: '',
      keyword: '',
    });
    const materialList = ref([]);
    const selectedMaterials = ref([]); // 选中的物料

    // 打开物料选择模态框
    const openMaterialDialog = () => {
      materialTable.value=[];
      axios.get('/api/WL/CGWL', {
        params: materialFilter,
      }).then((response) => {
        console.log(response.data);
        materialList.value = response.data;
      });
      materialDialogVisible.value = true;
    };

    // 处理物料选择
    const handleMaterialSelectionChange = (selection) => {
      selectedMaterials.value = selection;
    };

    // 确认选择物料
    const confirmMaterialSelection = () => {
      if (selectedMaterials.value.length > 0) {
        selectedMaterials.value.forEach((material) => {
          // 检查物料是否已经存在
          const isMaterialExist = form1.value.some(
            (item) => item.wl_code === material.wl_code
          );
          console.log(isMaterialExist);
          console.log('material', material);
          // 如果物料不存在，则添加到表格顶部
          if (!isMaterialExist) {
            form1.value.unshift({
              wl_code: material.wl_code,
              wl_name: material.wl_name,
              wl_dw_name: material.wl_dw_name,
              wl_dj: material.wl_dj,
            });
          }
        });
      }
      materialDialogVisible.value = false;
    };
    const deleteRow = (index) => {
  // 判断是否是默认的那行数据
  if (form1.value[index].wl_code === '') {
    ElMessage.error('默认行无法删除');
    return;
  }
  form1.value.splice(index, 1);
};
    // 计算小计
    const calculateSubtotal = (row) => {
      const quantity = parseFloat(row.yclcg_sl); // 将数量转换为数字
      const unitPrice = parseFloat(row.wl_dj); // 将单价转换为数字
      console.log(quantity, unitPrice);
      console.log(quantity, unitPrice);
      if (isNaN(quantity) || isNaN(unitPrice)) {
        row.yclcg_xj = 0; // 如果数量或单价无效，设置小计为 0
      } else {
        row.yclcg_xj = quantity * unitPrice; // 计算小计
      }
    };

    // 计算总
    const calculateTotal = () => {
      let total = 0;
      form1.value.forEach((item) => {
        total += parseFloat(item.yclcg_xj) || 0; // 将小计转换为数字并累加
      });
      return total.toFixed(2); // 保留两位小数
    };

    // 折扣金额
    const calculateDiscountratel = (form) => {
      const totalAmount = calculateTotal(); // 获取合计金额
      const discountRate = parseFloat(form.yclcg_zkl) || 0; // 获取折扣率并转换为数字

      if (isNaN(discountRate)) {
        form.yclcg_zkje = 0; // 如果折扣率无效，设置折扣金额为 0
      } else {
        // 计算折扣金额：合计金额-（合计金额 * (折扣率 / 100))
        form.yclcg_zkje = totalAmount - (totalAmount * (discountRate / 100)).toFixed(1);
      }
    };
    // 实收金额
    const calculateReceivedAmount = (form) => {
      const zk = parseFloat(form.yclcg_zkje) || 0;
      const fj = parseFloat(form.yclcg_fjje) || 0;

      form.yclcg_ssje = (calculateTotal() - zk + fj).toFixed(2);
      form.yclcg_zje = (calculateTotal() - zk).toFixed(2);

      console.log('计算后的实收金额', form.yclcg_ssje);
    };
    //获取仓库数据（下拉框）
    const fetchWarehouseOptions = async () => {
      try {
        const response = await axios.get('/api/Wbd_ck/Wbd_Ck');
        console.log(response.data);
        warehouseOptions.value = response.data.map(item => ({
          label: item.ck_name, // 假设返回的数据中仓库名称字段为 name
          value: item.ck_code    // 假设返回的数据中仓库 ID 字段为 id
        }));
      } catch (error) {
        console.error('获取仓库数据失败:', error);
      }
    };
    // 获取供应商数据（下拉框）
    const fetchgysOptions = async () => {
      try {
        const response = await axios.get('/api/KS/GetGYS');
        console.log(response.data);
        gysOptions.value = response.data.map(item => ({
          label: item.ks_name, // 假设返回的数据中仓库名称字段为 name
          value: item.ks_code    // 假设返回的数据中仓库 ID 字段为 id
        }))
      } catch (error) {
        console.error('获取供应商数据失败:', error);
      }
    }
    // 获取人员数据（下拉框）
    const fetchjsrOptions = async () => {
      jsrOptions.value = [
        { label: '张三', value: '1' },
        { label: '李四', value: '2' },
        { label: '王五', value: '3' },
        { label: '赵六', value: '4' },
      ]
    }


    // 搜索物料
    const searchMaterial = () => {
      console.log('搜索物料', materialFilter);
      // 这里可以调用接口获取物料列表
    };

    // 重置物料筛选条件
    const resetMaterialFilter = () => {
      materialFilter.type = '';
      materialFilter.keyword = '';
      searchMaterial();
    };
    // 文件验证
    const beforeUpload = (file) => {
      console.log('beforeUpload', file)
      const isValidSize = file.size / 1024 / 1024 <= 20
      if (!isValidSize) {
        ElMessage.error('文件大小不能超过20MB')
        return false
      }
      return true
    }

    // 处理成功上传
    // const handleSuccess = (response) => {
    //   console.log('handleSuccess', response)
    //   if (response.attachmentId) {
    //     ElMessage.success('文件上传成功')
    //   }
    // }
    const handleExceed = () => {
       ElMessage.error('超出上传文件数量限制');
    };


    // 分页切换
    const handleMaterialPageChange = (page) => {
      materialPagination.currentPage = page;
      searchMaterial();
    };
    const handleFileChange = (file, files) => {
      fileList.value = files // 手动更新文件列表
      //console.log('fileList', files)
    }

    const submitUpload = async () => {
      if (!fileList.value.length) {
        ElMessage.warning('请先选择文件')
        return
      }

    }
    const onSubmit = async () => {
      if (fileList.value.length === 0) {
        ElMessage.warning('请先上传附件')
        return
      }
      // 调用文件上传逻辑
      // await submitUpload()
    };


    const onSave = () => {
      console.log('保存', form.value);
      const data = {
        yclcg_code: form.value.yclcg_code,
        yclcg_ruck: form.value.yclcg_ruck,
        yclcg_gys: form.value.yclcg_gys,
        yclcg_ry: form.value.yclcg_ry,
        yclcg_time: form.value.yclcg_time,
        wl_code: '',
        yclcg_zkje: form.value.yclcg_zkje,
        yclcg_zkl: form.value.yclcg_zkl,
        yclcg_ssje: form.value.yclcg_ssje,
        yclcg_jsfs: form.value.yclcg_jsfs,
        yclcg_fjje: form.value.yclcg_fjje,
        djbz: form.value.djbz,
        yclcg_zje: form.value.yclcg_zje,
        create_by: userId.id,
        yclcg_sl: '',
        yclcg_djzt: 1,
      };
      console.log('保存', data);

      const data1 = form1.value.slice(0, -1).map(item => ({
        yclcg_code: form.value.yclcg_code,
        wl_code: item.wl_code,
        wl_name: item.wl_name,
        yclcg_sl: parseInt(item.yclcg_sl),
        yclcg_dw: item.wl_dw_name,
        yclcg_dj: item.wl_dj,
        yclcg_xj: item.yclcg_xj,
        bz: item.bz,
      }));

      if (data1.length === 0) {
        ElMessage.error('子表数据为空，无法保存');
        return;
      }

      data.wl_code = data1[0].wl_code;
      data.yclcg_sl = data1.reduce((acc, cur) => acc + (Number(cur.yclcg_sl) || 0), 0);

      console.log('保存1', data1);
      axios.post('/api/Rm_yclcg/Addyclcg', data)
        .then(response => {
          if (response.data) {
            ElMessage.success('保存成功');
            for (const item of form1.value.slice(0, -1)) {
              console.log('保存2', item);
              axios.post('/api/Rm_yclcgxq/Addyclcgxq', {
                yclcg_code: id,
                wl_code: item.wl_code,
                wl_name: item.wl_name,
                yclcg_sl: parseInt(item.yclcg_sl),
                yclcg_dw: item.wl_dw_name,
                yclcg_dj: item.wl_dj,
                yclcg_xj: item.yclcg_xj,
                bz: item.bz,
              })
                .then(response => {
                  if (response.data) {
                    ElMessage.success('保存成功');
                    router.push({ path: '/RawMaterialProcurement' });
                  }
                }).catch(error => {
                  console.error('保存失败:', error);
                });
            }
          }
        }).catch(error => {
          console.error('保存失败:', error);
        });

    };



    const onCancel = () => {
      console.log('取消');
      router.push({ path: '/RawMaterialProcurement' });
    };
    onMounted(() => {
      fetchWarehouseOptions();
      fetchgysOptions();
      fetchjsrOptions();
    });

    return {
      materialTable,
      form,
      materialDialogVisible,
      materialFilter,
      materialList,
      selectedMaterials,
      openMaterialDialog,
      handleMaterialSelectionChange,
      confirmMaterialSelection,
      calculateSubtotal,
      calculateTotal,
      calculateDiscountratel,
      searchMaterial,
      resetMaterialFilter,
      handleMaterialPageChange,
      handleExceed,
      onSubmit,
      onSave,
      onCancel,
      calculateReceivedAmount,
      warehouseOptions,
      gysOptions,
      jsrOptions,
      beforeUpload,
      // handleSuccess,
      submitUpload,
      handleFileChange,
      uploadData,
      uploadRef,
      form1,
      deleteRow

    };
  },
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-center {
  text-align: center;
  flex: 1;
  /* 让标题占据剩余空间，使其居中 */
}

.document-number {
  font-size: 14px;
  color: #666;
}

.el-table {
  margin-bottom: 20px;
  /* 表格与下方内容隔开 */
}

.el-table--border {
  border: 1px solid #ebeef5;
}

.el-table--border th,
.el-table--border td {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>